
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>websocket</title>
</head>
<body>
    <input type="text" id="text">
    <button onclick="send()">发送</button>
    <script type="text/javascript">
        let text = document.getElementById('text');
        var ws = new WebSocket("ws://localhost:8888"); //在客户端连接服务器
        // 当连接打开或者说建立连接后，会触发回调
        ws.onopen = function () {
            ws.send("server");
        };
        // 监听服务器发送给客户端
        ws.onmessage = function (event) {
            console.log('onmessage', event.data);
        };
        function send() {
            ws.send(text.value);
            text.value = '';
        }
    </script>
</body>
</html>